#include "kprocess.h"
#include "elfloader.h"
#include "memory.h"

/**
 * execute a kernel process application (elf)
 * @param elf: the elf binary
 * @param argc: the count of argument
 * @param argv: the value of argument
 * @return: the result of execution
 */
mx_size_t mx_kprocess_exec (mx_uint8_pt elf, mx_usize_t argc, char** argv)
{
    mx_size_t ret = -1;
    /* calculate the size of elf's allocable section */
    mx_usize_t size = mx_elfloader_memsize(elf);
    if (size > 0)
    {
        /* memory allocate for kapp */
        // mx_void_pt addr = mx_memory_alloc(size);
        // TODO: 这里等内存管理完善之后再作修改，对于 ARM64 架构，分配的内存需要是 4k 对齐的
        //       因此需要根据 MXSETUP_KAPP_LOAD_ALIGN 配置项来分配对齐的内存
        mx_void_pt addr = (mx_void_pt)0x40180000;
        if (addr != mx_null)
        {
            /* load kapp to memory and repaire it */
            kmain_pt kmain = mx_elfloader(elf, addr);
            if (kmain != mx_null)
            {
                /* run kapp */
                ret = kmain(argc, argv);
            }
        }
    }
    return ret;
}
